<?php

namespace App\Http\Controllers\Car;

use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use App\Models\Car\MortgageDetail;
use App\Models\Car\MortgageLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Modules\Car\Entities\RecognizeDrivingLicense;

class MortgageController extends Controller
{
    use ResponseData;
    public function index(MortgageLog $model,Request $request){
        $perPage = $request->input('size',10);
        if($request->filled('status')){
            $model = $model->where('status',$request->status);
        }
        if($request->filled('name')){
            $model = $model->where('order_sn','like','%'.$request->name.'%')
                ->orWhere('plate_numbers','like','%'.$request->name.'%');
        }

        $products = $model
            ->orderByRaw('all_number - returned_number ASC')
            ->paginate($perPage);
        return $this->success($products);
    }
    // 获取详情页接口
    public function detail(MortgageDetail $model,Request $request){
        $detail = $model->query()->where('order_sn',$request->order_sn)->orderByDesc('return_end')->get();
        $data = $detail->groupBy('plate_number');
        return $this->success($data);
    }
    protected function buildDetail($car,$request,$order_sn){
        // 按揭本期还款，当月任意一天都能操作
        $data = [];
        for ($i=1;$i<=$request->total_number;$i++){
            if($request->is_month==1){
                $start = Carbon::now()->addMonths($i-1)->startOfMonth();
                $end = Carbon::now()->addMonths($i-1)->endOfMonth();
            }else{
                $start = Carbon::now()->addMonths($i)->startOfMonth();
                $end = Carbon::now()->addMonths($i)->endOfMonth();
            }
            $data[$i-1]= [
                'serial_number'=>$i,// 还款期数
                'order_sn'=> $order_sn,
                'plate_number'=>$car['plate_number'],
                'number'=>$request->total_number,
                'money'=>$car['money'],
                'borrower'=>$car['borrower'],
                'return_start'=>$start,
                'return_end'=>$end
            ];
        }

        if(count($data)>0){
            DB::table('mortgage_details')->insert($data);
        }
    }
//$data = [
//'order_sn'=>$order_sn,
//'mark'=>$request->mark?$request->mark:'',
//'bank_name'=>$request->bank_name, // 按揭银行名称
//'days'=>$request->days, // 每月还款时间
//'plate_numbers'=>$request->plate_numbers, // 车牌号
//'total_number'=>$request->total_number, // 按揭期数
//'all_number'=>$request->all_number, // 总还款期数
//
//'total_amonut'=>$request->total_amonut, // 总还款金额
//'mortgage_amount'=>$request->mortgage_amount, // 按揭总额
//'interest'=>$request->interest, // 总还总利息
//
//'operator'=>$request->operator, // 操办人
//];
    public function store(MortgageLog $model,Request $request){
        $id = MortgageLog::query()->count('id');
        if(is_array($request->cars)){
            $cars = $request->cars;
        }else{
            $cars = json_decode($request->cars,true);
            info('获取到的cars数据',$cars);
        }
        DB::beginTransaction();
        $req = $request->only(["mark","bank_name","days","plate_numbers",
            "total_number","all_number","total_amonut","mortgage_amount",
            "interest","operator","cars","is_month"
        ]);
        $req['order_sn'] = 'adj'.date('Ymd',time()).($id+1);
        $model->query()->create($req);
        if($request->filled('days')&&$request->days>0){
            foreach($cars as $car){
                $this->buildDetail($car,$request,$req['order_sn']);
            }
        }

        DB::commit();
        return $this->success('保存成功');
    }
    public function update(MortgageLog $model,Request $request){
        $mortgage = $model->find($request->id);
        if(!$mortgage){
            return $this->failed('当前按揭不存在',201);
        }
        DB::beginTransaction();
        $req = $request->only(["mark","bank_name","days","plate_numbers",
            "total_number","all_number","total_amonut","mortgage_amount",
            "interest","operator","cars","is_month"
        ]);
        $req['returned_number'] = 0;
        $req['return_amount'] = '0.00';
        $mortgage->update($req);
        if(is_array($request->cars)){
            $cars = $request->cars;
        }else{
            $cars = json_decode($request->cars,true);
        }
        foreach($cars as $car){
            // 查找是否可删除
            // $isexit = $this->isDelete($car['plate_number']);
            // if($isexit){
            //     continue;
            // }else{
            //     MortgageDetail::query()->where('plate_number',$car['plate_number'])->delete();
            // }
            MortgageDetail::query()->where('plate_number',$car['plate_number'])->delete();
//           判断是否存在如果存在则更新，不存在则添加
            if($request->filled('days')&&$request->days>0){
                $this->buildDetail($car,$request,$mortgage->order_sn);
            }

        }

        DB::commit();
        return $this->success('修改成功');
    }
    // 根据条件进行判断是否可以删除
    public function destory(Request $request){
        MortgageLog::query()->where('order_sn',$request->order_sn)->delete();
        MortgageDetail::query()->where('order_sn',$request->order_sn)->delete();
        return $this->success('删除成功');
    }
    // 判断是否可删除
    protected function isDelete($plate_number){
        return MortgageDetail::query()->where('plate_number',$plate_number)
            ->where('status',2)->first();
    }
    // 操作还款功能
    public function repaymentSingle(MortgageDetail $model,Request $request){
        $data = $model->query()->where('plate_number',$request->plate_number)
            ->where('status',1)
            ->where('return_start','<',now())
            ->where('return_end','>',now())->first();
        if(!$data){
            return $this->failed('未找到本期所需还款金额',201);
        }
        $data->status= 2;
        $data->save();
        $mortgage = MortgageLog::query()->where('order_sn',$data->order_sn)->first();
        $map = [
          'returned_number'=>$mortgage->returned_number+1,
            'return_amount'=>$mortgage->return_amount+$data->money
        ];
        if($mortgage->returned_number+1==$mortgage->all_number){
            // 如果按揭完成了
            $map['status'] = 2;
        }
        // 更新总次数和总金额
        $mortgage->update($map);
        return $this->success('还款成功');
    }
    // 还款当前单号下面的数据
    protected function paymentBatch($order_sn){
        // 根据单号找到当前按揭明细里所有未还记录
        $list = MortgageDetail::query()->where('order_sn',$order_sn)
                ->where('status',1)
                ->where('return_start','<',now())
                ->where('return_end','>',now())->pluck('id')->toArray();
        if(count($list)>0){
            // 更新为已还
            $number=0;
            $mount=0;
            foreach ($list as $item){
                $data = MortgageDetail::find($item);
                $mount+=$data->money;
                $number++;
                $data->status = 2;
                $data->save();
            }
            // 根据单号找到按揭单数据
            $mortgage = MortgageLog::query()->where('order_sn',$order_sn)->first();
            $map = [
                'returned_number'=>$mortgage->returned_number+$number,
                'return_amount'=>$mortgage->return_amount+$mount
            ];
            if($mortgage->returned_number+$number==$mortgage->all_number){
                // 如果按揭完成了
                $map['status'] = 2;
            }
            // 更新总次数和总金额
            $mortgage->update($map);
        }
        // // 当前单号下面有多少数量和总计金额
        // $plate_form = MortgageDetail::query()
        //     ->select(DB::raw('SUM(money) as mount'),'COUNT(id) as number')
        //     ->where('order_sn',$order_sn)
        //     ->where('return_start','<',now())
        //     ->where('return_end','>',now())
        // ->first();
        // if($plate_form){
        //     $plate_form->replicate()->update(['status'=>2]);
        //     $mortgage = MortgageLog::query()->where('order_sn',$order_sn)->first();
        //     $map = [
        //         'returned_number'=>$mortgage->returned_number+$plate_form->number,
        //         'return_amount'=>$mortgage->returned_number+$plate_form->mount
        //     ];
        //     if($mortgage->returned_number+$plate_form->number==$mortgage->all_number){
        //         // 如果按揭完成了
        //         $map['status'] = 2;
        //     }
        //     // 更新总次数和总金额
        //     $mortgage->update($map);
        // }
    }
    // 批量还款
    public function repaymentBatch(MortgageDetail $model,Request $request){
        // 根据订单号 查找还款车牌号
        if(is_array($request->order_sn)){
            $map = $request->order_sn;
        }else{
            $map = json_decode($request->order_sn,true);
        }
        foreach ($map as $order_sn){
            $this->paymentBatch($order_sn);
        }
        return $this->success('批量还款成功');
    }
    // 获取可以按揭车辆列表
    public function isAuthMortgate(){
        $source = RecognizeDrivingLicense::query()->where('id','>',0)->whereNull('deleted_at')->pluck('plate_number');
        if(count($source)>0){
            $data = MortgageDetail::query()->where('id','>',0)->distinct()->pluck('plate_number');
            if($data){
                $res = $source->diff($data)->values()->toArray();
                $list = MortgageLog::query()->whereNotNull('plate_numbers')->pluck('plate_numbers');
                if($list->count()>0){
                    foreach ($list as $item){
                        $arr = explode('、',$item);
                        foreach ($arr as $key=>$value){
                            if(in_array($value,$res)){
                                $index = array_search($value, $res);
                                unset($res[$index]);
                            }
                        }
                    }
                }
                $res = array_values($res);
                return $this->success($res);
            }
        }
        return $this->success($source);

    }
    // 批量添加按揭单备注
    public function updateMark(MortgageLog $model,Request $request){
        $data = $model->find($request->id);
        if(!$data){
            return $this->failed('当前按揭不存在',201);
        }
        $logs = MortgageLog::query()->where('order_sn',$data->order_sn)->orderBy('id')->pluck('id')->toArray();
        foreach($logs as $log){
            $isCar = MortgageLog::query()->where('id',$log)->first();
            if($isCar){
                $isCar->mark = $request->mark?$request->mark:'';
                $isCar->updated_at = now();
                $isCar->save();
            }
        }
        return $this->success('修改成功');
    }
    // 单个结清
    public function RemainingSettlement(MortgageDetail $model, Request  $request){
        DB::beginTransaction();
        $model = $model->query()
            ->where('status',1)
            ->where('plate_number',$request->plate_number);
        $amount = $this->getAmount(clone  $model);
        $number = $this->getNumber(clone  $model);
        // 批量更新还款状态
        $model->update(['status'=>2]);
        // 获取当前记录
        $log = MortgageLog::query()->where('order_sn',$request->order_sn)->first();
        if($log->all_number==$log->returned_number+$number){
            // 如果按揭完成了
            $log->status = 2;
        }
        $log->return_amount = $log->return_amount+$amount;
        $log->returned_number = $log->returned_number+$number;
        $log->save();
        DB::commit();
        return $this->success('结清成功');
    }
    protected function getAmount($model){
        return $model->sum('money');
    }
    protected function getNumber($model){
        return $model->count('id');
    }
    public function getBatchList(Request $request,MortgageDetail $model){
        if($request->filled('list')){
            if(is_array($request->list)){
                $list = $request->list;
            }else{
                $list = json_decode($request->list,true);
            }
            $data = $model->whereIn('order_sn',$list)
                ->where('return_start','<',now())
                ->where('return_end','>',now())
                ->get();
            return $this->success($data);
        }
    }
}
